package zozopo.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;




public class URLFilter implements Filter { 
    public void doFilter(ServletRequest servletRequest, ServletResponse     
                              servletResponse, FilterChain filterChain) throws  
                                        IOException,ServletException 
    { 
       HttpServletRequest request = (HttpServletRequest) servletRequest; 
       HttpServletResponse response = (HttpServletResponse) servletResponse; 
       //String realPath =request.getSession().getServletContext().getRealPath("/"); 

       String uri = request.getServletPath();
       String path = request.getRequestURI();
       String rewriteUrl = getRewriteUrl(uri);
      // rewriteUrl = "http://www.zozopo.com" + rewriteUrl;
       if (null != rewriteUrl) {
    	   request.setCharacterEncoding("UTF-8");
    	   RequestDispatcher rd = request.getRequestDispatcher(path+rewriteUrl);
    	   rd.forward(request, response); 
           //response.sendRedirect("view.action");
           return;
       }
       
       filterChain.doFilter(servletRequest, servletResponse); 

    } 

public String getRewriteUrl(String url) { 

	int iIndex = url.lastIndexOf("/");
	int pointIndex = url.lastIndexOf(".");
	
	String headStr = url.substring(0, iIndex);
	String lastStr = url.substring(iIndex+1, pointIndex);
	
	String[] str = lastStr.split("_");
	
	StringBuffer retStr = new StringBuffer();
	retStr.append(headStr);
	retStr.append("/");
	retStr.append(str[0]);
	retStr.append(".action?");
	retStr.append(str[1]);
	retStr.append("=");
	retStr.append(str[2]);
		
	//headStr + "/"+str[0]+".action?"+str[1]+"=" + str[2];
	
	return retStr.toString();

}

public void destroy() {
	// TODO Auto-generated method stub
	
}

public void init(FilterConfig filterConfig) throws ServletException {
	// TODO Auto-generated method stub
	
} 

} 

